< previous page page_445 next page >

Page 445
After youve added several Employee objects to the employee collection, you can now retrieve one of those objects. To do this, you fill in the text box in the Search For Employee frame. After filling in a unique key value, click the Display command button. The code for the Click event of this command button is presented here:
9f31265bb40b592b1929e18a47ab28e5.gif
Private Sub cmdDisplay_Click()
   Dim oEmp As Employee

   ' Retrieve Search Criteria from Collection
   Set oEmp = mcolEmps.Item(txtSearch)

   ' Display the Employee Name
   oEmp.EmployeeName
End Sub
If you type the value 1 in the text box, this value is passed as a parameter to the Item() method of the Collection object. Because this is a string value, the Item method searches through the Key properties in the collection to find the element that matches this key. If the element is found, a reference to the object in the collection is returned to the oEmp variable. Because this is pointing to a valid Employee object, you can now invoke any of the methods on the Employee class (such as the EmployeeName method, for example). If the element is not found, a trappable error occurs. Therefore, its a good idea to add some error handling any time youre using the Item method.
Problems with Public Collections
Although the preceding implementation seems to work fine, there are some problems with it. The problem with the Collection class is that youre allowed to put any object into each element. This means that an Employee object could be in the first element, and a form reference could be in the second element. This is not a problem as long as you know what youre doing, but the idea of a collection is that it stores objects that are all of the same type. By storing objects that are all of the same type, you can iterate over the collection and perform a group operation on each element in the collection. If you store two different object types, youll receive an error if you try to store an element in an object variable thats expecting a different object type.

 
< previous page page_445 next page >

If you like this book, buy it!